package okex

import (
	"blockchain_data/handler/model"
	"blockchain_data/handler/okex/response"
	"blockchain_data/handler/okex/ws"
	"blockchain_data/middleware"
	"blockchain_data/utils"
	"blockchain_data/utils/errmsg"
	"fmt"
	"github.com/sirupsen/logrus"
	"strconv"
	"sync"
	"time"
)
var log *logrus.Logger
var WsTradeMap sync.Map

type OkTickSave struct {
	middleware.SaveData
}

// 订阅合约需要初始化，取消订阅不需要
func TickInit(goods string, contractCode string, bourse string, server string) *OkTickSave {
	wsOkex := new(ws.WSMarketClient).Init()
	OkTickSave := new(OkTickSave)

	OkTickSave.Init(goods,contractCode,bourse,server,wsOkex)
	return OkTickSave
}

// 订阅tick数据
func (this *OkTickSave)SubTrade(ch chan model.Msg)  {
	client := this.Ws.(*ws.WSMarketClient)
	//定时删除数据
	this.DeleteTradeDetail(7 * 24 * time.Hour,"30 1 * * *")
	client.SubTradeDetail(this.ContractCode, ch ,func(trade *response.Trade) {
		datas := trade.Data
		for _,data := range datas {
			ts := data.Ts
			bourse := this.Bourse
			price := data.Px
			amount := data.Sz
			direction := data.Side
			ts_temp,_ := strconv.ParseInt(ts,10,64)
			ts8 := utils.NaniUnixToStr(ts_temp,"2006-01-02D15:04:05.000000")
			s := fmt.Sprintf("%s,%s,%s,%s,%s,%s,%s\n",ts,bourse,this.ContractCode,price,amount,direction,ts8)
			this.SaveTradeDetail(s)
		}
	})
	WsTradeMap.Store(this.Goods+this.Server+this.ContractCode,this)
}

// 取消价格订阅
func (this *OkTickSave)UnSubTrade() int {
	client := this.Ws.(*ws.WSMarketClient)
	// 关闭ws连接
	client.Close()
	// 停止定时删除任务
	this.CloseDeleteTradeDetail()
	return errmsg.SUCCESS_SUB
}
